import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
import routes from './routes'
import 'font-awesome/css/font-awesome.min.css'
import axios from 'axios'
import '@/common/js/permission'





//配置axios的全局基本路径
axios.defaults.baseURL = 'http://localhost:8080';
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

const router = new VueRouter({
  routes
})

//前置拦截器  每次请求都要携带token
axios.interceptors.request.use(req=>{
    let token = localStorage.getItem("token")
    if(token){
        req.headers["token"] = token
    }
    return req
},error => {
    Promise.reject(error)
})

axios.interceptors.response.use(res=>{
    if(res.data.success === false || res.data.code === 900){
        localStorage.removeItem("menus")
        localStorage.removeItem("userinfo")
        localStorage.removeItem("permissions")
        localStorage.removeItem("token")
        router.push({ path: '/login' });//跳转
    }
    return res
})

//每次路由之前都要执行,每次请求都要经过路由
//每次请求都不拦截到
router.beforeEach((to, from, next) => {
  //NProgress.start();
  if (to.path == '/login' || to.path == '/register') {
    //重新登录,把原来session移除掉
      localStorage.removeItem("menus")
      localStorage.removeItem("userinfo")
      localStorage.removeItem("permissions")
      localStorage.removeItem("token")
  }
  next();
})


//处理页面刷新动态路由失效问题
initIndexRouters();
function initIndexRouters(){
    if(!localStorage.menus){
        return;
    }
    //防止重复配置路由：4就是main.js中路由的个数 - 如果你的静态路由是6个这里要写成6
    if(router.options.routes.length>4){
        return;
    }
    let menus = localStorage.getItem('menus');
    menus = JSON.parse(menus);
    let tempRouters = [];
    menus.forEach(menu=>{
        let indexRouter = {
            path: '/',
            iconCls: menu.icon,
            name: menu.name,
            component: resolve => require(['@/views/Home'], resolve),
            children: []
        }
        if(menu.children){
            menu.children.forEach(cMenu=>{
                let cr = {
                    path: cMenu.url,
                    name: cMenu.name,
                    component: resolve => require(['@/views/'+cMenu.component], resolve)
                }
                indexRouter.children.push(cr)
            })
        }
        tempRouters.push(indexRouter)
        router.options.routes.push(indexRouter)
    })
    //动态路由配置
    router.addRoutes(tempRouters);
}



new Vue({
  router,
  store,
  render: h => h(App) // index.html id为app的div标签下面使用<App/>和template: '<App/>',一样的效果
}).$mount('#app') // 和el: '#app'效果一样都是挂载在index.html id为app的div标签上面

